<?php
$cs = Yii::app()->clientScript;
$cs->registerCoreScript('jquery');
$cs->registerCoreScript('bbq');
$cs->registerScriptFile(Yii::app()->themeManager->baseUrl.'/Admin/scripts/fancybox/jquery.fancybox-1.3.4.custom.js', CClientScript::POS_END);
$cs->registerScriptFile(Yii::app()->themeManager->baseUrl.'/Admin/scripts/fancybox/jquery.easing-1.3.pack.js', CClientScript::POS_END);
$cs->registerCssFile(Yii::app()->themeManager->baseUrl.'/Admin/scripts/fancybox/jquery.fancybox-1.3.4.custom.css');
$cs->registerCssFile(Yii::app()->themeManager->baseUrl.'/Admin/styles/toolbar.css');
$urlManager = Yii::app()->urlManager;
if ($this->isEditMode())
{
    $cs->registerCoreScript('jquery.ui');
    $cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/jquery.site-builder.js', CClientScript::POS_END);
    //        $cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/jquery.site-builder.toolbar.js', CClientScript::POS_END);
    $cs->registerCssFile(Yii::app()->theme->baseUrl.'/styles/site-builder.css');
    $baseUrl = $urlManager->createUrl('/Core/service/ajax');
    $script = "
jQuery.page_changed = false;
jQuery('.sb-container')
    .bind('order_changed.sbcontainer', function(event, data){
        jQuery('.toolbar .edit-mode li').hide();
        jQuery('.toolbar .edit-mode .save, .toolbar .edit-mode .new, .toolbar .edit-mode .cancel').show();
        jQuery.page_changed= true;
    })
    .bind('before_delete_widget.sbcontainer', function(event, data){
        var page_id = 0;
        var matchs = jQuery('body').attr('class').match(/page_(\d+)/);
        if (matchs && matchs.length == 2)
            page_id = parseInt(matchs[1]);
        jQuery.ajax({
            async : false,
            url : '{$baseUrl}',
            data : {
                'SID' : 'Cms.pageWidget.canDeleteWidget',
                'page_id' : page_id,
                'widget_data_id' : data.inst.get_widget_instance_id(data.rslt.obj)
            },
            success : function(res){
                res = eval(res);
                if (res.errors != undefined && res.errors.length <= 0) {
                    if (res.allowDelete != undefined && res.allowDelete)
                    {
                        if (!confirm('Are you sure want to delete this widget?'))
                            data.inst.data.core.allow_delete = false;
                    }
                    else
                        data.inst.data.core.allow_delete = false;
                } else {
                    var message = 'Error';
                    if (jQuery.isArray(res.errors.ErrorCode))
                        message = res.errors.ErrorCode.join('. ');
                    alert(message);
                    data.inst.data.core.allow_delete = false;
                }
            },
            error : function(){
                if (!confirm('Are you sure want to delete this widget?'))
                    data.inst.data.core.allow_delete = false;
            }
        });
    })
    .bind('create_widget.sbcontainer', function(event, data){
        if (data.rslt.obj.length)
            currentRef = data.rslt.obj;
        currentContainer = data.inst;
        var container = data.inst.get_container_id();
        var url = jQuery.param.querystring('".Yii::app()->request->hostInfo.$urlManager->createUrl('/Cms/admin/pageWidget/create', array('page_id'=>$this->controller->pageId,'revision_id'=>$this->controller->pageRevision, 'layout'=>'popup'))."', {'container' : container});
        jQuery.loadPage(url);
    })
    .bind('edit_widget.sbcontainer', function(event, data){
        //console.log('edit widget');
        var page_widget_id = data.inst.get_page_widget_id(data.rslt.obj);
        var url = jQuery.param.querystring(decodeURIComponent(data.rslt.obj.attr('rel')), {'page_widget_id' : page_widget_id, 'layout': 'popup'});
        jQuery.loadPage(url);
    })
    .bind('change_layout_widget.sbcontainer', function(event, data){
        var page_widget_id = data.inst.get_page_widget_id(data.rslt.obj);
        var widget_layout_id = data.inst.get_widget_layout_id(data.rslt.obj);
        var url = jQuery.param.querystring('".Yii::app()->request->hostInfo.$urlManager->createUrl('/Cms/admin/pageWidget/layout', array('layout'=>'popup'))."', {'page_widget_id' : page_widget_id, 'widget_layout_id' : widget_layout_id});
        jQuery.loadPage(url);
    })
    .bind('duplicate_widget.sbcontainer', function(event, data){
        var valid = false;
        if (jQuery('#sb-page-controls').hasClass('live'))
        {
            alert('Sorry but this function is not available on LIVE workflow');
        }
        else if (jQuery('#sb-nav-save-position').is(':hidden') == false)
        {
             if (confirm('All changes you made on this page will be saved. If you are not sure to save other changes, reload the page and copy again.'))
             {
                jQuery.save_position(false, true);
                valid = true;
             }
        }
        else
            valid = true;
        
        if (valid)
        {
            var page_widget_id = data.inst.get_page_widget_id(data.rslt.ref);
            var url = jQuery.param.querystring('".$urlManager->createUrl('/Core/service/ajax', array('SID'=>'Cms.pageWidget.duplicateData'))."', {'page_widget_id' : page_widget_id});
            jQuery.get(url, function(res){
                window.location = window.location.href.replace(/\#.*/, '');
            });
        }
    })
    .sbcontainer();

var currentRef = null;
var currentContainer = null;
jQuery.addWidget = function(html)
{
    var obj = jQuery(html);
    currentContainer.add_widget(obj, currentRef, 'after');
    currentRef = null;
}

//save change
jQuery('.toolbar .edit-mode li.save a').click(function(){
    jQuery.save_position();
    return false;
});

//new revision
jQuery('.toolbar .edit-mode li.new a').click(function(){
    jQuery.fancybox({
        width: 500,
        height: 200,
        padding: 0,
        margin: 0,
        showCloseButton : false,
        hideOnOverlayClick : false,
        type: 'inline',
        href: '#new-revision-log'
    });
    return false;
});
";
    $cs->registerScript(__CLASS__.'#initSiteBuilder', $script);
}
$script = "
jQuery('.toolbar .menu li').mouseover(function(){
    jQuery('.toolbar .menu li').removeClass('active');
    jQuery(this).addClass('active');
});
jQuery('.toolbar .edit-mode li').mouseout(function(){
    jQuery(this).removeClass('active');
});
jQuery('.toolbar .edit-mode li.cancel a').click(function(){
    if (confirm('Are you sure?'))
    {
        window.location = window.location.href.replace(/\#.*/, '');
    }
    return false;
});
jQuery('body').addClass('toolbar-drawer');
jQuery('.change-mode').click(function(){
    jQuery.get(jQuery(this).attr('href'), function(){window.location = window.location.href.replace(/\#.*/, '');});    
    return false;
});
";
$cs->registerScript(__CLASS__.'InitMenuItems', $script);
$script = "
jQuery('.toolbar a[href!=\"#\"]:not(\'.disabled\'), a.fancybox-popup')
    .click(function(){
        var selected = jQuery(this);
        var href = jQuery.param.querystring(selected.attr('href'), {layout: 'popup'});
        selected.attr('href', href);
    })
    .fancybox({
        'width' : '100%',
        'height' : '100%',
        'padding' : 0,
        'margin' : 0,
        'top' : 0,
        'scrolling' : 'yes',
        'model' : true,
        'autoScale' : false,
        'hideOnOverlayClick' : false,
        'autoDimensions' : false,
        'titleShow' : false,
        'titlePosition' : 'outside',
        'transitionIn' : 'face',
        'transitionOut' : 'face',
        'easingIn' : 'linear',
        'easingOut' : 'linear',
        'onStart' : function(selectedArray, selectedIndex, selectedOpts){
            jQuery('body').addClass('overlay-open');
        },
        'onClosed' : function(){
            jQuery('body').removeClass('overlay-open');
        },
        'type': 'iframe'
    });
jQuery.loadPage = function(href){
    jQuery.fancybox({
        'width' : '100%',
        'height' : '100%',
        'padding' : 0,
        'margin' : 0,
        'top' : 0,
        'scrolling' : 'yes',
        'model' : true,
        'autoScale' : false,
        'hideOnOverlayClick' : false,
        'autoDimensions' : false,
        'titleShow' : false,
        'titlePosition' : 'outside',
        'transitionIn' : 'face',
        'transitionOut' : 'face',
        'easingIn' : 'linear',
        'easingOut' : 'linear',
        'onStart' : function(selectedArray, selectedIndex, selectedOpts){
            jQuery('body').addClass('overlay-open');
        },
        'onClosed' : function(){
            jQuery('body').removeClass('overlay-open');
        },
        'href': href,
        'type': 'iframe'
    });
}
";
$cs->registerScript(__CLASS__.'Popup', $script);
$script = "
jQuery.save_position = function(new_revision){
    var containers = {},
        new_revision = new_revision != undefined ? new_revision : 0,
        set_active = 1,
        is_preview = ".(int) Yii::app()->request->getParam('revision', 0).",
        url = '".$urlManager->createUrl('/Core/service/ajax', array('SID'=>'Cms.pageWidget.savePosition' , 'page_id'=>$this->controller->pageId, 'revision'=>$this->controller->pageRevision))."';
    jQuery.each(jQuery('.sb-container'), function(){
        var container_id = jQuery(this).attr('id');
        containers[container_id] = [];
        var widgets = jQuery('.sb-widget', this);
        jQuery.each(widgets, function(){
            var page_widget_id = parseInt(jQuery(this).attr('id').replace('page_widget_', ''));
            if (page_widget_id != NaN)
                containers[container_id].push(page_widget_id);
        });
    });
    
    if ($(containers).size());
    {
        if (is_preview)
        {
            set_active = 0;
            if (confirm('This revision is not active in any workflow, do you want to activate it?'))
            {
                set_active = 1;
            }
        }
        var data = {
            'containers' : containers,
            'new_revision' : new_revision,
            'set_active' : set_active
        };
        if (jQuery.log != null)
            data = jQuery.extend(data, {'log' : jQuery.log});
        jQuery.ajax({
            type : 'get',
            async : new_revision,
            url : url,
            data : data ,
            success : function(){
                //show menu items
                jQuery('.toolbar .edit-mode li').show();
                jQuery('.toolbar .edit-mode .save, .toolbar .edit-mode .cancel').hide();
                jQuery('#new-revision-log').parent().hide();
                
                jQuery.page_changed = false;
                if (new_revision && is_preview)
                {
                    jQuery.get('".$urlManager->createUrl('/Core/service/ajax', array('SID'=>'Cms.pageRevision.getNextRevision', 'page_id'=>$this->controller->pageId))."', function(res){
                        res = eval(res);
                        if (res.revision != undefined)
                        {
                            var lastest_revision  = parseInt(res.revision)-1;
                            window.location = window.location.href.replace(/revision=\\d+/, 'revision='+lastest_revision);
                        }
                    });
                }
                if (new_revision)
                {
                    alert('Page content is saved into a new revision.');
                    window.location = window.location.href.replace(/\#.*/, '');
                }
                else
                {
                    alert('Page content is saved in the same revision.');
                }
            }
        });
    }
    return false;
};
";
$cs->registerScript(__CLASS__.'#SavePosition', $script);
?>
<div id="indition-toolbar" class="toolbar">
    <a class="logo" href="#" title="Home"><img src="<?php echo Yii::app()->theme->baseUrl;?>/images/logo.png" alt="Site Logo" /></a>
    <?php $this->widget('zii.widgets.CMenu', array(
        'items'=>$items,
        'encodeLabel'=>false,
        'htmlOptions'=>array(
            'class'=>'menu'.($this->isEditMode() ? ' edit-mode' : '')
        )
    ));?>
    <ul class="user-info">
        <li><?php echo CHtml::link('Hello '.user()->getState('username'), array('/User/account/update'), array('title'=>'Edit account', 'class'=>'fancybox-popup'));?></li>
        <li class="last">
            <?php echo CHtml::ajaxLink('Logout', array('/Core/service/command', 'SID'=>'Core.Account.cmdLogout'), array('success'=>'js:function(){window.location = window.location.href.replace(/\#.*/, \'\');}'), array('title'=>'Logout'));?>
        </li>
    </ul>
</div>
<?php
$script = "
jQuery('body').delegate('#new-revision-log-form .ok', 'click', function(){
    var text = jQuery('#fancybox-content #new-revision-log-form #log_message').val();
    var str = text.replace(/\s+/m, '');
    if (str.length)
    {
        jQuery('#new-revision-log-form .error').hide();
        jQuery.log = text;
        jQuery.save_position(1);
    }
    else
        jQuery('#new-revision-log-form .error').show();
});
jQuery('body').delegate('#new-revision-log-form .cancel', 'click', function(){
    jQuery.fancybox.close();
    jQuery('#new-revision-log-form .error').hide();
});
";
$cs->registerScript(__CLASS__.'#InputLogInfo', $script);
?>
<div style="display: none;">
<div id="new-revision-log">
    <div class="title">New Revision</div>
    <div id="new-revision-log-form">        
        <div class="row error" style="display: none;">You must enter a log message for the new revision</div>
        <div class="row">
            <?php echo CHtml::label('Log Message', 'log_message');?>
        </div>
        <div class="row">
            <?php echo CHtml::textArea('log_message', '', array('cols'=>70, 'rows'=>7));?>
        </div>
        <div class="buttons">
            <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
            <?php echo CHtml::button('New Revision', array('class'=>'ok'));?>
        </div>
    </div>
</div>
</div>
<?php 
$script='
	$.each($(".toolbar li li li > a"),function() {
		$(this).find("span").unwrap();
	});
';
$cs->registerScript(__CLASS__.'#ONLOAD', $script);
?>